<template>
  <div class="content" v-loading="formLoading">
    <div class="routeHeader mb-5px">
    <el-button
      type="primary"
      @click="submitForm"
      v-hasPermi="['salary:accounting-workshop-staff-score:save']"
    >
      保存
    </el-button>
    <el-button
      plain
      @click="goBack"
    >
      关闭
    </el-button>
  </div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="登记日期" prop="registerDate">
        <el-date-picker
          v-model="formData.registerDate"
          type="date"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          placeholder="选择开始登记日期"
        />
      </el-form-item>
      <el-form-item label="员工工号" prop="jobNumber">
        <el-select
          v-model="formData.jobNumber"
          placeholder="请输入员工工号"
          filterable
          clearable
          remote
          reserve-keyword
          class="!w-220px"
          :remote-method="getJobNumberList"
          :loading="remoteLoading"
          @change="selectJobNumeber"
        >
        <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.jobNumber"
          :value="item.jobNumber"
         />
        </el-select>
      </el-form-item>
      <el-form-item label="员工姓名" prop="staffName">
        <!-- <el-input v-model="formData.staffName" placeholder="请输入员工姓名" /> -->
        <el-select
          v-model="formData.staffName"
          placeholder="请输入员工姓名"
          filterable
          clearable
          remote
          reserve-keyword
          class="!w-220px"
          :remote-method="getStaffNameList"
          @change="selectStaffName"
        >
        <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.staffName"
          :value="item.staffName"
         />
        </el-select>
      </el-form-item>
      <el-form-item label="岗位" prop="dictPost">
        <el-select v-model="formData.dictPost" placeholder="请输入岗位" disabled>
          <el-option
            v-for="dict in getIntDictOptions('config_post')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班组编码" prop="teamCode">
        <el-input v-model="formData.teamCode" placeholder="请输入班组编码" disabled />
      </el-form-item>
      <el-form-item label="所属班组" prop="teamName">
        <el-input v-model="formData.teamName" placeholder="请输入所属班组" disabled />
      </el-form-item>
      <el-form-item label="班组人数" prop="teamMembers">
        <el-input v-model="formData.teamMembers" placeholder="请输入班组人数" @input="validateInput('teamMembers')" />
      </el-form-item>
      <el-form-item label="条件" prop="conditions">
        <el-input 
        v-model="formData.conditions"
         type="textarea" 
         placeholder="请输入条件" 
        maxlength="50" 
        show-word-limit
        style="width: 350px"/>
      </el-form-item>
      <el-form-item label="标准" prop="standard">
        <el-input v-model="formData.standard" placeholder="请输入标准" @input="validateInput('standard')" />
      </el-form-item>
      <el-form-item label="基准产值" prop="standardOutput">
        <el-input v-model="formData.standardOutput" placeholder="请输入基准产值"  @input="validateInput('standardOutput')" />
      </el-form-item>
      <el-form-item label="基准人数" prop="standardMembers">
        <el-input v-model="formData.standardMembers" placeholder="请输入基准人数"  @input="validateInput('standardMembers')" />
      </el-form-item>
      <el-form-item label="当月产值" prop="monthOutput">
        <el-input v-model="formData.monthOutput" placeholder="请输入当月产值" @input="validateInput('monthOutput')" />
      </el-form-item>
      <el-form-item label="当月人数" prop="monthMembers">
        <el-input v-model="formData.monthMembers" placeholder="请输入当月人数" @input="validateInput('monthMembers')" />
      </el-form-item>
      <el-form-item label="当月基准" prop="monthStandard">
        <el-input v-model="formData.monthStandard" placeholder="请输入当月基准" @input="validateInput('monthStandard')" disabled/>
      </el-form-item>
      <el-form-item label="绩效" prop="performance">
        <el-input v-model="formData.performance" placeholder="请输入绩效"  @input="validateInput('performance')" />
      </el-form-item>
      <el-form-item label="实发" prop="actualPayment">
        <el-input v-model="formData.actualPayment" placeholder="请输入实发" disabled/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input 
        v-model="formData.remark"
         type="textarea" 
         placeholder="请输入备注" 
        maxlength="50" 
        show-word-limit
        style="width: 350px"/>
      </el-form-item>
    </el-form>
</div>
</template>
<script setup lang="ts">
import { getIntDictOptions } from '@/utils/dict'
import * as AccountingLeaderSubsidyApi from '@/api/payroll/shopWagesCalculate/accountingLeaderSubsidy'
import { useTagsViewStore } from '@/store/modules/tagsView'
const { query } = useRoute() // 路由的查询
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
// const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({})
const formRules = reactive({
  registerData: [{ required: true, message: '登记日期不能为空', trigger: 'blur' }],
  jobNumber: [{ required: true, message: '员工工号不能为空', trigger: 'change' }],
  staffName: [{ required: true, message: '员工姓名不能为空', trigger: 'change' }],
  standard: [{ required: true, message: '标准不能为空', trigger: 'blur' }],
  standardOutput: [{ required: true, message: '基准产值不能为空', trigger: 'blur' }],
  standardMembers: [{ required: true, message: '基准人数不能为空', trigger: 'blur' }],
  monthOutput: [{ required: true, message: '当月产值不能为空', trigger: 'blur' }],
  monthMembers: [{ required: true, message: '当月人数不能为空', trigger: 'blur' }],
  performance: [{ required: true, message: '绩效不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref
const remoteLoading = ref(false)//远程搜索loading


const options =ref([])
// 获取员工工号
const getJobNumberList = async (query: string) => {
  remoteLoading.value = true
  try {
    const data = await AccountingLeaderSubsidyApi.getStaffList({
      pageNo: 1,
      pageSize: 10,
      jobNumber:query})
    options.value = data.list
  } finally {
    remoteLoading.value = false
  }
}

// 获取员工姓名
const getStaffNameList = async (query: string) => {
  remoteLoading.value = true
  try {
    const data = await AccountingLeaderSubsidyApi.getStaffList({
      pageNo: 1,
      pageSize: 10,
      staffName:query})
    options.value = data.list
  } finally {
    remoteLoading.value = false
  }
}

const selectJobNumeber = ()=>{
  options.value.map((item)=>{
    if (formData.value.jobNumber === item.jobNumber){
      formData.value.staffName = item.staffName
      formData.value.dictStaffType = item.dictStaffType
      formData.value.teamCode = item.teamCode
      formData.value.teamName = item.teamName
      formData.value.dictPost = item.dictPost
    }
  })
}

const selectStaffName = ()=>{
  options.value.map((item)=>{
    if (formData.value.staffName === item.staffName){
      formData.value.jobNumber = item.jobNumber
      formData.value.dictStaffType = item.dictStaffType
      formData.value.teamCode = item.teamCode
      formData.value.teamName = item.teamName
    }
  })
}

let inputVal = ref([])
// 只能填写数字，允许小数点后 2/4位数
const validateInput = (val) => {
  formData.value[val] = formData.value[val].replace(/[^0-9.]/g, ''); 
  const decimalParts =  formData.value[val].split('.');
    if(decimalParts[0] == '')formData.value[val] = ''
if (decimalParts.length > 2) {
  formData.value[val] = decimalParts[0] + '.' + decimalParts[1]
}
if(inputVal.value.indexOf(val)==-1)inputVal.value.push(val)
};

const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  inputVal.value.forEach((item)=>{
    formData.value[item] = parseFloat(formData.value[item]);
  })
  try {
    const data = formData.value as unknown as AccountingWorkshopStaffScoreApi.AccountingWorkshopStaffScoreVO
    if (query.type === 'create') {
      await AccountingLeaderSubsidyApi.createAccountingLeaderSubsidy(data)
      message.success(t('common.createSuccess'))
    } else {
      await AccountingLeaderSubsidyApi.updateAccountingLeaderSubsidy(data)
      message.success(t('common.updateSuccess'))
    }
    goBack()
  } finally {
    formLoading.value = false
  }
}

const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = async() => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  //跳转列表页
  route.push({
    path:'/payroll/payroll/shopWagesCalculate/accountingLeaderSubsidy'
  })
}

// /** 重置表单 */
// const resetForm = () => {
//   formData.value = {
//     id: undefined,
//     beginRegisterData: undefined,
//     endRegisterData: undefined,
//     jobNumber: undefined,
//     staffName: undefined,
//     teamCode: undefined,
//     teamName: undefined,
//     coefficientScore: undefined,
//     performanceAssessScore: undefined,
//     totalAttendanceSkyNumber: undefined,
//     insideFactorySkyNumber: undefined,
//     outsideFactorySkyNumber: undefined,
//     roadSkyNumber: undefined,
//     totalOvertimeHour: undefined,
//     insideFactoryOvertimeHour: undefined,
//     outsideFactoryOvertimeHour: undefined,
//     overtimeSalary: undefined,
//     dictStaffType: undefined,
//     remark: undefined,
//     creatorName: undefined,
//     updaterName: undefined,
//     updateTime: undefined
//   }
//   formRef.value?.resetFields()
// }

onMounted(async () => {
// const datePickerHeader = await document.querySelector('.el-date-picker__header');
//     if (datePickerHeader) {
//       datePickerHeader.style.display = 'none';
//     }
if(query.type == "update"){
 const res = await AccountingLeaderSubsidyApi.getAccountingLeaderSubsidy(query.id)
 console.log(res)
 formData.value = res
}
})

</script>
<style lang="scss" scoped >
.content {
  padding: 10px;
  background: #fff;
}
::v-deep .el-input__suffix {
  display:none;
}

::v-deep .el-year-table .today .cell {
  color: #606266 !important;
  font-weight: 100 !important;
}
</style>
